package com.shiningstars.php;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;

import com.shiningstars.general.Constants;
import com.shiningstars.general.Utilities;

public class JSONParser implements Constants {

	public JSONObject getJSONFromUrl(Context context, String url, List<NameValuePair> params)
			throws IllegalStateException, IOException, JSONException {

		DefaultHttpClient httpClient = new DefaultHttpClient();
		HttpPost httpPost = new HttpPost(url);
		httpPost.setEntity(new UrlEncodedFormEntity(params));

		HttpResponse httpResponse = httpClient.execute(httpPost);
		HttpEntity httpEntity = httpResponse.getEntity();
		InputStream is = httpEntity.getContent();

		BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
		StringBuilder sb = new StringBuilder();

		String line = null;
		while ((line = reader.readLine()) != null) {
			sb.append(line + "n");
		}

		is.close();

		JSONObject jsonObject = null;

		try {
			jsonObject = new JSONObject(sb.toString());
		} catch (JSONException e) {
			Utilities.logError(context, JSONParser.class.getName(), e, params.toString(), sb.toString());
			throw e;
		}

		return jsonObject;
	}
}